package com.wsc.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.wsc.entity.Student;
import com.wsc.service.StudentService;
import com.wsc.utils.ExportExcelUtil;
import com.wsc.utils.ImportBeanExcel;

@RestController
@CrossOrigin(origins = "*", maxAge = 3600) // 前后端分离 实现跨域访问
@RequestMapping("student")
public class StudentController {
	@Autowired
	private StudentService ss;

	// 添加
	@RequestMapping("add")
	public Integer add(Student stu) {
		return ss.add(stu);
	}

	// 删除
	@RequestMapping("deleteById")
	public Integer deleteById(Integer id) {
		// 一个id字段，jpa识别不了是student还是membership的id
		return ss.deleteById(id);
	}

	@RequestMapping("deleteByIds")
	public Integer deleteByIds(String ids) {
		Integer target = 0;
		// id字符串转成字符串数组
		String[] list = ids.split(",");
		for (int i = 0; i < list.length; i++) {
			// String转Integer 调用单删方法 循环实现多删
			target = ss.deleteById(Integer.valueOf(list[i]));
		}
		return target;
	}

	// 修改
	@RequestMapping("update")
	public Integer update(Student stu) {
		return ss.update(stu);
	}

	/***
	 * 查询所有 分页 模糊查询 id cardno name sex membershipid status reark stuno
	 */
	@RequestMapping("getAllStu")
	public Map<String, Object> getAllStu(String cardno, String name, Integer membershipid, String stuno, Integer status,
			Integer limit, Integer page) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("cardno", cardno);
		params.put("name", name);
		params.put("membershipid", membershipid);
		params.put("stuno", stuno);
		params.put("status", status);
		limit = limit == null ? 10 : limit;
		page = page == null ? 0 : page - 1;
		params.put("limit", limit);
		params.put("page", page);
		return ss.getAllStu(params);
	}

	// 导入 校验 Integer类型不能
	@RequestMapping("/importStudent")
	public Map<String, Object> importDept(MultipartFile file) {
		Map<String, Object> map = new HashMap<String, Object>();
		// Excel有效数据总数（除去标题、表头）
		Integer count = 0;
		// 成功导入的数据总数
		Integer importCount = 0;
		// 读取excel表格
		try {
			List<List<String>> lists = ImportBeanExcel.readExcel(file.getInputStream());
			// 判断集合是否为空 list集合存储的是List<String>类型
			if (!CollectionUtils.isEmpty(lists)) {
				for (int i = 1; i < lists.size(); i++) {
					count = lists.size() - 1;
					// 判断Excel是否首行表名，次行表头，三行数据
					if ("卡号".equals(lists.get(i).get(0))) {
						count--;
						i++;
					}
					// 一整条数据
					List<String> list = lists.get(i);
					// 卡号
					String cardno = list.get(0);
					// 姓名
					String name = list.get(1);
					// 性别
					String sex = list.get(2);
					// 身份编号 获取excel表中的数字为Double类型需要转Integer
					Double membershipidD = Double.parseDouble(list.get(3));
					Integer membershipid = new Double(membershipidD).intValue();
					// 状态
					Double statusD = Double.parseDouble(list.get(4));
					Integer status = new Double(statusD).intValue();
					// 学号
					String stuno = list.get(5);
					// 备注
					String reark = list.get(6);
					Student stu = new Student(null, cardno, name, sex, membershipid, status, reark, stuno, null);
					try {
						// add方法有校验
						importCount += ss.add(stu);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			// 导入总数据数量
			map.put("count", count);
			// 导入未重复数据数量
			map.put("importCount", importCount);
		} catch (IOException e) {
			map.put("count", 0);
			map.put("importCount", importCount);
			e.printStackTrace();
		}
		return map;
	}

	// 导出 使用无回调函数提交方式
	@RequestMapping("/exportStudent")
	public void export(HttpServletRequest request, HttpServletResponse response, String ids) {
		// excel sheeet标题
		String title = "学生表";
		// excel表名
		String[] headers = { "卡号", "姓名", "性别", "身份编号", "状态", "学号", "备注" };
		// excel文件名
		String fileName = title + System.currentTimeMillis() + ".xls";
		// String转String数组
		String[] arr = ids.split(",");
		// List of Teacher Type
		List<Map<String, Object>> list = new ArrayList<>();
		// HashSet集合去除重复id
		HashSet<Integer> hs = new HashSet<Integer>();
		for (int i = 0; i < arr.length; i++) {
			// String转Integer
			Integer id = Integer.parseInt(arr[i]);
			// 数组元素添加到HashSet去重复
			hs.add(id);
		}
		for (Integer id : hs) {
			Student s = ss.getOne(id);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("cardno", s.getCardno());
			map.put("name", s.getName());
			map.put("sex", s.getSex());
			map.put("membershipid", s.getMembershipid());
			map.put("status", s.getStatus());
			map.put("stuno", s.getStuno());
			map.put("remark", s.getReark());
			list.add(map);
		}
		// excel元素 "卡号", "姓名", "性别", "身份编号", "状态", "学号","备注"
		String content[][] = new String[list.size()][3];
		for (int i = 0; i < list.size(); i++) {
			content[i] = new String[headers.length];
			content[i][0] = list.get(i).get("cardno").toString();
			content[i][1] = list.get(i).get("name").toString();
			content[i][2] = list.get(i).get("sex").toString();
			content[i][3] = list.get(i).get("membershipid").toString();
			content[i][4] = list.get(i).get("status").toString();
			content[i][5] = list.get(i).get("stuno").toString();
			// get(i)和get("key") 必须存在，若不存在即为null，会报NullPointerException
			Object remark = list.get(i).get("remark") == null ? "" : list.get(i).get("remark");
			content[i][6] = remark.toString();

		}
		// 创建HSSFWorkbook
		HSSFWorkbook wb = ExportExcelUtil.getHSSFWorkbook(title, headers, content);
		// 响应到客户端
		try {
			this.setResponseHeader(response, fileName);
			OutputStream os = response.getOutputStream();
			wb.write(os);
			os.flush();
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 发送响应流方法
	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			response.setContentType("application/octet-stream;charset=Utf-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
